﻿using AspectCore.DynamicProxy;
using RAP.Framework.Libary.DataSource.Model.Attribute;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using RAP.Framework.Libary.Utils;
using System.Reflection;
using System.Collections.Concurrent;

namespace RAP.Framework.Libary.DataSource.Model.Interceptor
{
    /// <summary>
    /// 抽象的懒加载关系数据的拦截器
    /// </summary>
    public abstract class AbstractLazyLoadInterceptor : AbstractInterceptor
    {
        /// <summary>
        /// 属性的get方法名称前缀
        /// </summary>
        public const string PROPERTY_GET_PREFIX = "get_";

        /// <summary>
        /// 
        /// </summary>
        public static ConcurrentDictionary<MethodInfo, InterceptorContext> InterceptorMethodCaches = new ConcurrentDictionary<MethodInfo, InterceptorContext>();

        /// <summary>
        /// 
        /// </summary>
        protected static object _lockObject = new object();

        /// <summary>
        /// 根据切面上下文对象获取拦截方法的相关参数
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static InterceptorContext GetInterceptorContext ( AspectContext context )
        {
            var method = context.ImplementationMethod;
            if ( !InterceptorMethodCaches.TryGetValue( method, out var interceptorContext ) )
            {
                lock ( _lockObject )
                {
                    if ( !InterceptorMethodCaches.TryGetValue( method, out interceptorContext ) )
                    {
                        var methodName = method.Name;
                        if ( methodName.StartsWith( PROPERTY_GET_PREFIX ) )
                        {
                            methodName = methodName.Substring( PROPERTY_GET_PREFIX.Length );
                        }
                        var memberInfo = method.DeclaringType.GetMember( methodName ).FirstItem();
                        var hasLazyLoadAttribute = memberInfo.HasAttribute<LazyloadAttribute>();
                        if ( hasLazyLoadAttribute )
                        {
                            var methodInfo = memberInfo as MethodInfo;
                            var isAsync = context.IsAsync();

                            interceptorContext = new InterceptorContext
                            {
                                Name = methodName,
                                LazyLoadAttr = memberInfo.GetCustomAttribute<LazyloadAttribute>(),
                                MemberInfo = memberInfo,
                                IsAsync = isAsync
                            };
                            InterceptorMethodCaches.TryAdd( method, interceptorContext );
                        }
                        else
                        {
                            InterceptorMethodCaches.TryAdd( method, null );
                        }
                    }
                }
            }
            return interceptorContext;
        }

        /// <summary>
        /// 拦截方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task Invoke ( AspectContext context, AspectDelegate next )
        {
            var sourceModelObject = context.Implementation as IDataModel;
            var interceptorContext = GetInterceptorContext( context );
            if ( interceptorContext != null )
            {
                //执行数据库查询
                var queryResult = await QueryData( sourceModelObject, context, interceptorContext );

                if ( context.Parameters.Length > 0 )
                {
                    //最后一个参数作为查询结果传入被拦截的函数
                    context.Parameters[ context.Parameters.Length - 1 ] = queryResult;
                }
                else
                {
                    context.ReturnValue = queryResult;//如果是拦截属性的get方法，则直接返回查询结果
                    return ;
                }
            }
            await next( context );
        }

        /// <summary>
        /// 执行数据查询
        /// </summary>
        /// <param name="sourceModelObject"></param>
        /// <param name="context"></param>
        /// <param name="interceptorContext"></param>
        /// <returns></returns>
        protected virtual async Task<object> QueryData ( IDataModel sourceModelObject, AspectContext context, InterceptorContext interceptorContext )
        {
            return await Task.FromResult<object>( null );
        }
    }
}
